package com.shop.utils;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;

/**
 * 
 * @Title HttpClientUtil</p>
 * @Project runlin-framework
 * @Package com.runlin.framework.util
 * @author Kevin Lv
 * @date 2016年8月15日 下午4:16:17
 * @version V1.0
 */
@SuppressWarnings("deprecation")
public class HttpClientUtil {

	/**
	 * 
	* @Title: doGet
	* @Description: HttpClient - Get 请求
	* @param @param url
	* @param @param param
	* @param @return    设定文件
	* @return String    返回类型
	* @throws
	 */
	public static String doGet(String url, Map<String, String> param) {

		CloseableHttpClient httpclient = HttpClients.createDefault();
		String resultString = "";
		CloseableHttpResponse response = null;
		try {
			URIBuilder builder = new URIBuilder(url);
			if (param != null) {
				for (String key : param.keySet()) {
					builder.addParameter(key, param.get(key));
				}
			}
			URI uri = builder.build();
			HttpGet httpGet = new HttpGet(uri);
			response = httpclient.execute(httpGet);
			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(),"UTF-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}

	/**
	 * 
	* @Title: doGet
	* @Description: HttpClient - Get不带参数请求
	* @param @param url
	* @param @return    设定文件
	* @return String    返回类型
	* @throws
	 */
	public static String doGet(String url) {
		return doGet(url, null);
	}

	/**
	 * 
	* @Title: doPost
	* @Description: HttpClient - Post带参数请求
	* @param @param url
	* @param @param param
	* @param @return    设定文件
	* @return String    返回类型
	* @throws
	 */
	public static String doPost(String url, Map<String, String> param) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			HttpPost httpPost = new HttpPost(url);
			if (param != null) {
				List<NameValuePair> paramList = new ArrayList<>();
				for (String key : param.keySet()) {
					paramList.add(new BasicNameValuePair(key, param.get(key)));
				}
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
						paramList,"UTF-8");
				httpPost.setEntity(entity);
			}
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return resultString;
	}

	/**
	 * 
	* @Title: doPost
	* @Description: HttpClient - Post不带参数请求
	* @param @param url
	* @param @return    设定文件
	* @return String    返回类型
	* @throws
	 */
	public static String doPost(String url) {
		return doPost(url, null);
	}

	/**
	 * 
	* @Title: doPostJson
	* @Description: HttpClinet - 返回Json
	* @param @param url
	* @param @param json
	* @param @return    设定文件
	* @return String    返回类型
	* @throws
	 */
	public static String doPostJson(String url, String json) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			HttpPost httpPost = new HttpPost(url);
			StringEntity entity = new StringEntity(json,ContentType.APPLICATION_JSON);
			httpPost.setEntity(entity);
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}
	
    /**
     * 
     * 场景：客户端(浏览器)A---->选择文件上传---->服务器B---->中转文件---->服务器C---->返回结果---->服务器B---->客户端A
		有时候在项目中需要把上传的文件中转到第三方服务器，第三方服务器提供一个接收文件的接口。
		而我们又不想把文件先上传到服务器保存后再通过File来读取文件上传到第三方服务器，我们可以使用HttpClient来实现。
    * @Title: httpClientUploadFile
    * @Description: 模拟文件上传
    * @param @param file
    * @param @param remoteUrl
    * @param @return    设定文件
    * @return String    返回类型
    * @throws
     */
    public static String httpClientUploadFile(MultipartFile file,String remoteUrl) {
    	
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        try {
            String fileName = file.getOriginalFilename();
            HttpPost httpPost = new HttpPost(remoteUrl);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
            builder.addTextBody("filename", fileName);// 类似浏览器表单提交，对应input的name和value
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);// 执行提交
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                // 将响应内容转换为字符串
                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
	
	/**
	 * 上传多媒体文件
	 * @param access_token
	 * @param type 图片（image）、语音（voice）、视频（video）和缩略图（thumb）
	 * 图片（image）: 1M，支持JPG格式
	 * 语音（voice）：2M，播放长度不超过60s，支持AMR\MP3\SPEEX格式
	 * 视频（video）：10MB，支持MP4格式
	 * 缩略图（thumb）：64KB，支持JPG格式
	 * @param filePath
	 * @return
	 * @throws IOException
	 */
	public static String uploadMedia(String access_token, String type,String filePath) throws IOException {
		
		String mediaId = null;
		CloseableHttpResponse response = null;
		String url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token="+ access_token + "&type=" + type;
		
		CloseableHttpClient httpclient = null;
		httpclient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		FileBody bin = new FileBody(new File(filePath));
		MultipartEntity mpEntity = new MultipartEntity(); // 文件传输
		mpEntity.addPart("media", bin);
		httpPost.setEntity(mpEntity);
		try {
			response = httpclient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {
				HttpEntity entity = response.getEntity();
				String jsonString = EntityUtils.toString(entity);
				
				JSONObject jsonObj = JSONObject.parseObject(jsonString);
				Object mediaObj = jsonObj.get("media_id");
				if (null != mediaObj) {
					mediaId = mediaObj.toString();
				}
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(response != null){
				response.close();
			}
			if(httpclient!= null){
				httpclient.close();
			}
		}
		return 	mediaId;
	}
	
}
